use std::error::Error;
use std::fs;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};

pub fn run() -> Result<(), Box<dyn Error>> {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    let mut i = 0;
    for stream in listener.incoming() {
        let stream = stream.unwrap();

        i += 1;
        //println!("request: {}", i);
        handle_connection(stream);
    }

    Ok(())
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = vec![0; 1024];
    let received_len = stream.read(&mut buffer).unwrap();

    println!(
        "Request, len = {}: {}",
        received_len,
        String::from_utf8_lossy(&buffer[..])
    );

    let get = b"POST / HTTP/1.1\r\n";

    let (status_line, file_name) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK", "hello.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND", "404.html")
    };

    //buffer.find("Content-Type");

    let reply = "nothing";

    let response = format!(
        "{}\r\nContent-Length: {}\r\n\r\n{}",
        status_line,
        reply.len(),
        reply
    );
    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}
